<template>
    <div class="chat-page">
        <!-- 页面标题 -->
        <div class="page-header">
            <el-page-header content="AI对话系统" @back="handleBack" class="page-header__inner"></el-page-header>
        </div>
        <!-- 主体内容：左侧会话列表 + 右侧聊天区域 -->
        <div class="chat-container">
            <!-- 左侧：会话管理 -->
            <div class="session-sidebar">
                <!-- 会话操作栏 -->
                <div class="session-action">
                    <el-button 
                        type="primary" 
                        icon="Plus" 
                        size="small" 
                        @click="handleCreateSession"
                        class="session-action__create"
                    >
                        新对话
                    </el-button>
                    <el-button 
                        icon="Delete" 
                        size="small" 
                        type="text" 
                        @click="handleDeleteSession" 
                        :disabled="!selectedSessionId"
                        class="session-action__delete"
                    >
                        删除对话
                    </el-button>
                </div>

                <!-- 会话列表 -->
                <el-scrollbar class="session-list-container">
                    <div 
                        v-for="(session, index) in sessionList" 
                        :key="session.session_id"
                        class="session-item"
                        :class="{ 'session-item--active': session.session_id === selectedSessionId }"
                        @click="handleSelectSession(session.session_id, index)"
                        @mouseenter="hoverSessionIndex = index"
                        @mouseleave="hoverSessionIndex = -1"
                    >
                        <!-- 会话标题 + 编辑按钮（hover显示） -->
                        <div class="session-item__header">
                            <div class="session-item__title">
                                {{ session.title || '未命名对话' }}

                            </div>
                            <el-button 
                                icon="Edit" 
                                size="mini" 
                                type="text" 
                                class="session-item__edit"
                                v-if="hoverSessionIndex === index"
                                @click.stop="handleEditSessionTitle(session)"
                            ></el-button>
                        </div>
                        <!-- 会话时间 -->
                        <div class="session-item__time">
                            {{ utils.formateDate(new Date(session.updated_at)) }}
                        </div>
                    </div>
                </el-scrollbar>

                <!-- 参数配置（折叠面板） -->
                <el-collapse 
                    class="chat-config" 
                    v-model="activeConfigName"
                    accordion
                >
                    <el-collapse-item 
                        title="对话参数配置" 
                        name="config"
                        class="chat-config__item"
                    >
                        <el-form 
                            :model="chatConfig" 
                            label-width="100px" 
                            size="small"
                            class="chat-config__form"
                        >
                            <!-- 系统提示词 -->
                            <el-form-item label="系统提示词" class="chat-config__form-item">
                                <el-input 
                                    v-model="chatConfig.sys_prompt" 
                                    type="textarea" 
                                    rows="3" 
                                    placeholder="请输入系统提示词（定义AI角色）"
                                    class="chat-config__input"
                                />
                            </el-form-item>
                            
                            <!-- 历史轮数 -->
                            <el-form-item label="历史保留轮数" class="chat-config__form-item">
                                <el-slider 
                                    v-model="chatConfig.history_len" 
                                    :min="1" 
                                    :max="10" 
                                    :step="1"
                                    show-input
                                    class="chat-config__slider"
                                />
                            </el-form-item>
                            
                            <!-- 采样温度 -->
                            <el-form-item label="采样温度" class="chat-config__form-item">
                                <el-slider 
                                    v-model="chatConfig.temperature" 
                                    :min="0.01" 
                                    :max="1.0" 
                                    :step="0.01"
                                    show-input
                                    class="chat-config__slider"
                                />
                            </el-form-item>
                            
                            <!-- 采样概率 -->
                            <el-form-item label="采样概率" class="chat-config__form-item">
                                <el-slider 
                                    v-model="chatConfig.top_p" 
                                    :min="0.01" 
                                    :max="1.0" 
                                    :step="0.01"
                                    show-input
                                    class="chat-config__slider"
                                />
                            </el-form-item>
                            
                            <!-- 最大Token -->
                            <el-form-item label="最大Token数" class="chat-config__form-item">
                                <el-slider 
                                    v-model="chatConfig.max_token" 
                                    :min="64" 
                                    :max="4096" 
                                    :step="64"
                                    show-input
                                    class="chat-config__slider"
                                />
                            </el-form-item>
                            
                        </el-form>
                    </el-collapse-item>
                </el-collapse>
            </div>

            <!-- 右侧：聊天区域 -->
            <div class="chat-main">
                <!-- 聊天顶部栏（会话标题 + 清空按钮） -->
                <div class="chat-main__header" v-if="selectedSessionId">
                    <div class="chat-main__title">
                        {{ getCurrentSessionTitle() || '新对话' }}
                    </div>
                    <el-button 
                        type="text" 
                        icon="Delete" 
                        size="small" 
                        @click="handleClearHistory"
                        :disabled="chatHistory.length === 0 || isSending"
                        class="chat-main__clear-btn"
                    >
                        清空记录
                    </el-button>
                </div>

                <!-- 聊天记录区域 -->
                <el-scrollbar class="chat-history-container" ref="chatScrollbar">
                <div class="chat-history">
                    <!-- 1. 无选中会话：显示“请选择或创建对话” -->
                    <div class="no-session-hint" v-if="!selectedSessionId">
                    <div class="no-session-hint__inner">
                        <el-empty description="请选择或创建一个对话"></el-empty>
                    </div>
                    </div>

                    <!-- 2. 有选中会话：显示空历史提示 / 历史记录 / 加载中 -->
                    <div v-else>
                    <!-- 2.1 有会话但无历史：显示“开始对话”提示 -->
                    <div class="empty-hint" v-if="chatHistory.length === 0">
                        <div class="empty-hint__inner">
                        <el-empty 
                            description="开始与AI助手对话吧～"
                            class="empty-hint__empty"
                        >
                            <template #image>
                            <div class="empty-hint__icon">
                                <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" color="#c0c4cc">
                                <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"></path>
                                <path d="M12 13a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-1a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2z"></path>
                                </svg>
                            </div>
                            </template>
                        </el-empty>
                        <div class="empty-hint__tips">
                            你可以询问技术问题、获取生活建议，或让AI帮你创作内容
                        </div>
                        </div>
                    </div>

                    <!-- 2.2 有会话且有历史：显示聊天记录 -->
                    <div class="message-list" v-else>
                        <div 
                        v-for="msg in chatHistory" 
                        :key="msg.message_id"
                        class="message-item"
                        :class="`message-item--${msg.role}`"
                        >
                        <!-- 消息内容（补充用户/AI头像，优化显示） -->
                        <div class="message-item__avatar">
                            <el-avatar :icon="msg.role === 'user' ? User : 'Robot'" size="small" />
                        </div>
                        <div class="message-item__content">
                            <div class="message-item__nickname">
                            {{ msg.role === 'user' ? '我' : 'AI助手' }}
                            </div>
                            <div 
                            class="message-item__text" 
                            v-html="formatMessage(msg.content)"
                            ></div>
                            <div class="message-item__time">
                            {{ utils.formateDate(new Date(msg.created_at || new Date())) }}
                            </div>
                        </div>
                        </div>
                    </div>


                    </div>
                </div>
                </el-scrollbar>

                <!-- 输入区域 -->
               <div class="chat-input-container" :class="{ 'chat-input-container--disabled': !selectedSessionId }">
                <div class="input-form">
                    <textarea
                    v-model="inputForm.query"
                    rows="3"
                    placeholder="请输入您的问题..."
                    @keydown.enter.prevent="handleSendMessage"
                    :disabled="isSending || !selectedSessionId"
                    class="input-form__textarea"
                    resize="none"
                    ></textarea>
                    
                    <div class="input-form__action">
                    <div class="input-form__tips">
                        <span v-if="isSending" class="input-form__sending">发送中...</span>
                        <span v-else>按Enter键发送消息</span>
                    </div>
                    <el-button 
                        type="primary" 
                        @click="handleSendMessage"
                        :loading="isSending"
                        :disabled="!selectedSessionId || !inputForm.query?.trim()"
                        class="input-form__send-btn"
                    >
                        发送
                    </el-button>
                    </div>
                </div>
                </div>
            </div>
        </div>

        <!-- 会话标题编辑弹窗 -->
        <el-dialog 
            title="编辑对话标题" 
            v-model="isEditTitleShow"
            width="30%"
            destroy-on-close
            :before-close="handleCancelEditTitle"
        >
            <el-form 
                :model="editTitleForm" 
                ref="editTitleFormRef"
                label-width="80px"
                class="edit-title-form"
            >
                <el-form-item 
                    label="标题" 
                    prop="title"
                    :rules="[
                        { required: true, message: '请输入标题', trigger: 'blur' },
                        { max: 30, message: '标题长度不能超过30个字符', trigger: 'blur' }
                    ]"
                >
                    <el-input 
                        v-model="editTitleForm.title" 
                        placeholder="请输入对话标题"
                        class="edit-title-form__input"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleCancelEditTitle">取消</el-button>
                    <el-button type="primary" @click="handleSaveTitle">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getCurrentInstance, onMounted, reactive, ref, nextTick, watch } from 'vue'
import utils from '@/utils/utils.js'
import { 
    ElMessage, 
    ElEmpty, 
    ElSkeleton, 
    ElScrollbar, 
    ElPageHeader,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
    ElSlider,
    ElSwitch,
    ElCollapse,
    ElCollapseItem,
    ElAvatar
} from 'element-plus'
import { 
  User, // 导入用户图标
} from '@element-plus/icons-vue'


export default {
    name: 'Chat',
    components: {
        
        ElEmpty,
        ElSkeleton,
        ElScrollbar,
        ElPageHeader,
        ElDialog,
        ElForm,
        ElFormItem,
        ElInput,
        ElButton,
        ElSlider,
        ElSwitch,
        ElCollapse,
        ElCollapseItem,
        ElAvatar
    },
    setup() {
        // 获取全局实例
        const { proxy } = getCurrentInstance()
        // 工具函数
        const $utils = utils

        // 1. 状态管理
        const currentUserId = ref(proxy.$store.state.userInfo.userId || '1') // 当前登录用户ID
        const sessionList = ref([]) // 会话列表
        const selectedSessionId = ref('') // 当前选中的会话ID
        const chatHistory = ref([]) // 聊天历史记录
        const inputForm = reactive({ query: '' }) // 输入表单
        const chatConfig = reactive({ // 对话参数配置
            sys_prompt: '你是一个非常可爱的助手，回答问题时要友好、简洁',
            history_len: 3,
            temperature: 0.5,
            top_p: 0.5,
            max_token: 512,
            stream: false
        })
        const activeConfigName = ref(['config']) // 折叠面板激活项
        const isSending = ref(false) // 发送状态
        const isStreaming = ref(false) // 流式输出状态
        const chatScrollbar = ref(null) // 聊天滚动容器引用
        const hoverSessionIndex = ref(-1) // 会话hover索引
        const isEditTitleShow = ref(false) // 编辑标题弹窗状态
        const editTitleForm = reactive({ title: '', sessionId: '' }) // 编辑标题表单
        const editTitleFormRef = ref(null) // 编辑标题表单引用

        // 2. 生命周期钩子
        onMounted(async () => {
            await getSessionList()
            // 默认选中第一个会话
            if (sessionList.value.length > 0) {
                handleSelectSession(sessionList.value[0].session_id)
            }
        })

        // 3. 监听选中会话变化
        watch(selectedSessionId, () => {
            nextTick(() => scrollToBottom())
        })

        // 4. 核心方法
        /**
         * 获取用户会话列表
         */
        const getSessionList = async () => {
            try {
                const res = await proxy.$api.getChatSessions({ user_id: currentUserId.value })
                sessionList.value = res || []
            } catch (error) {
                ElMessage.error('获取会话列表失败：' + (error.message || '网络异常'))
            }
        }

        /**
         * 创建新会话
         */
        const handleCreateSession = async () => {
            try {
                const res = await proxy.$api.createChatSession({
                    user_id: String(currentUserId.value),
                    title: '新对话'
                })
                sessionList.value.unshift(res)
                handleSelectSession(res.session_id)
                inputForm.query = ''
                ElMessage.success('新对话创建成功')
            } catch (error) {
                ElMessage.error('创建会话失败：' + (error.message || '网络异常'))
            }
        }

        /**
         * 选择会话（加载历史记录）
         */
        const handleSelectSession = async (sessionId) => {
            console.log('点击传递的 sessionId：', sessionId); 
            if (!sessionId) {
                console.error('传递的 sessionId 无效！');
                return; // 如果无效，直接返回，避免后续操作
            }

            selectedSessionId.value = sessionId;

            chatHistory.value = []
            try {
                const res = await proxy.$api.getChatHistory({
                    session_id: sessionId,
                    user_id: currentUserId.value
                })
                console.log("正确的历史记录响应：", res); // 此时 res 应包含 history 数组
                chatHistory.value = res.history || []
                console.log('加载历史后 chatHistory.value ：', chatHistory.value )
            } catch (error) {
                ElMessage.error('加载历史记录失败：' + (error.message || '网络异常'))
            }
        }

        /**
         * 删除会话
         */
        const handleDeleteSession = async () => {
            if (!selectedSessionId.value) return

            proxy.$confirm('确定要删除当前对话吗？删除后历史记录将无法恢复', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    await proxy.$api.deleteChatSession({
                        session_id: selectedSessionId.value,
                        user_id: currentUserId.value
                    })
                    // 从列表中移除
                    sessionList.value = sessionList.value.filter(
                        item => item.session_id !== selectedSessionId.value
                    )
                    // 重置状态
                    selectedSessionId.value = ''
                    chatHistory.value = []
                    ElMessage.success('对话删除成功')
                } catch (error) {
                    ElMessage.error('删除对话失败：' + (error.message || '网络异常'))
                }
            }).catch(() => {
                // 取消删除
            })
        }

        /**
         * 发送消息
         */
        const handleSendMessage = async () => {
            // 验证输入
            if (!inputForm.query.trim()) {
                ElMessage.warning('请输入您的问题')
                return
            }
            if (!selectedSessionId.value) {
                await handleCreateSession()
                if (!selectedSessionId.value) return
            }

            // 保存用户消息到历史
            const userMsg = {
                role: 'user',
                content: inputForm.query.trim(),
                created_at: new Date()
            }
            chatHistory.value.push(userMsg)
            const userInput = inputForm.query.trim()
            inputForm.query = ''
            scrollToBottom()

            // 准备请求参数
            const requestParams = {
                query: userInput,
                sys_prompt: chatConfig.sys_prompt,
                history: chatHistory.value.slice(0, -1),
                history_len: chatConfig.history_len,
                temperature: chatConfig.temperature,
                top_p: chatConfig.top_p,
                max_token: chatConfig.max_token,
                stream: false, // 强制设置为非流式
                session_id: selectedSessionId.value,
                user_id: String(currentUserId.value)
            }

            // 发送请求
            isSending.value = true
            
            try {
                // 使用非流式接口
                const response = await proxy.$api.chat(requestParams)
                
                // 添加AI回复到历史
                const aiMsg = {
                    role: 'assistant',
                    content: response,
                    created_at: new Date()
                }
                chatHistory.value.push(aiMsg)
                
                scrollToBottom()
                ElMessage.success('对话完成')
            } catch (error) {
                console.error('对话请求错误:', error)
                let errorMsg = '对话失败：'
                if (error.response) {
                    errorMsg += `服务器错误: ${error.response.status}`
                    if (error.response.data) {
                        try {
                            const errorData = JSON.parse(await error.response.data.text())
                            errorMsg += ` - ${errorData.detail || errorData.message}`
                        } catch (e) {
                            errorMsg += ' - 无法解析错误详情'
                        }
                    }
                } else {
                    errorMsg += error.message || '网络异常'
                }
                
                ElMessage.error(errorMsg)
            } finally {
                isSending.value = false
                isStreaming.value = false
            }
        }

        /**
         * 清空当前会话历史
         */
        const handleClearHistory = () => {
            proxy.$confirm('确定要清空当前对话记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                chatHistory.value = []
                ElMessage.success('记录清空成功')
            }).catch(() => {
                // 取消清空
            })
        }

        /**
         * 滚动到聊天底部
         */
        const scrollToBottom = () => {
            nextTick(() => {
                // 多层判断，确保 DOM 存在
                if (!chatScrollbar.value) return;
                const scrollContainer = chatScrollbar.value.$refs.wrap;
                if (!scrollContainer) return;
                // 确保元素已挂载到文档中
                if (scrollContainer.isConnected) {
                    scrollContainer.scrollTop = scrollContainer.scrollHeight;
                }
            })
        }

        /**
         * 格式化消息内容（支持换行）
         */
        const formatMessage = (content) => {
            // 先判断 content 是否存在，避免 undefined 报错
            if (!content || typeof content !== 'string') {
                return '';
            }
            // 替换换行符为 <br>，支持多行显示
            return content.replace(/\n/g, '<br>');
        }

        /**
         * 返回上一页
         */
        const handleBack = () => {
            proxy.$router.go(-1)
        }

        /**
         * 获取当前会话标题
         */
        const getCurrentSessionTitle = () => {
            const currentSession = sessionList.value.find(
                item => item.session_id === selectedSessionId.value
            )
            return currentSession?.title
        }

        /**
         * 编辑会话标题
         */
        const handleEditSessionTitle = (session) => {
            editTitleForm.title = session.title || ''
            editTitleForm.sessionId = session.session_id
            isEditTitleShow.value = true
        }

        /**
         * 保存会话标题
         */
        const handleSaveTitle = async () => {
            await editTitleFormRef.value.validate()
            try {
                await proxy.$api.updateSessionTitle({
                    session_id: editTitleForm.sessionId,
                    user_id: currentUserId.value,
                    title: editTitleForm.title
                })
                // 更新本地会话列表
                const sessionIndex = sessionList.value.findIndex(
                    item => item.session_id === editTitleForm.sessionId
                )
                if (sessionIndex !== -1) {
                    sessionList.value[sessionIndex].title = editTitleForm.title
                    sessionList.value = [...sessionList.value]
                }
                ElMessage.success('标题修改成功')
                isEditTitleShow.value = false
            } catch (error) {
                ElMessage.error('修改失败：' + (error.message || '网络异常'))
            }
        }

        /**
         * 取消编辑标题
         */
        const handleCancelEditTitle = () => {
            editTitleFormRef.value.resetFields()
            isEditTitleShow.value = false
        }

        // 暴露变量和方法
        return {
            utils: $utils,
            currentUserId,
            sessionList,
            selectedSessionId,
            chatHistory,
            inputForm,
            chatConfig,
            activeConfigName,
            isSending,
            isStreaming,
            chatScrollbar,
            hoverSessionIndex,
            isEditTitleShow,
            editTitleForm,
            editTitleFormRef,
            getSessionList,
            handleCreateSession,
            handleSelectSession,
            handleDeleteSession,
            handleSendMessage,
            handleClearHistory,
            handleBack,
            formatMessage,
            getCurrentSessionTitle,
            handleEditSessionTitle,
            handleSaveTitle,
            handleCancelEditTitle,
            User,
        }
    }
}
</script>

<style lang="scss" scoped>
// 全局样式变量
$primary-color: #165DFF;
$light-primary: #E8F3FF;
$user-color: #E6F7FF;
$assistant-color: #F5F7FA;
$text-primary: #303133;
$text-secondary: #606266;
$text-tertiary: #909399;
$border-color: #E4E7ED;
$hover-color: #F5F7FA;
$radius: 6px;
$shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

.chat-page {
    width: 100%;
    height: 100vh;
    padding: 16px;
    box-sizing: border-box;
    background-color: #F9FAFB;
    overflow: hidden;
}

// 页面标题样式
.page-header {
    margin-bottom: 16px;
    &__inner {
        background-color: white;
        padding: 12px 16px;
        border-radius: $radius;
        box-shadow: $shadow;
    }
}

// 主体容器
.chat-container {
    display: flex;
    width: 100%;
    height: calc(100% - 60px); // 减去标题高度
    gap: 16px;
}

// 左侧会话侧边栏
.session-sidebar {
    width: 320px;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: white;
    border-radius: $radius;
    box-shadow: $shadow;
    overflow: hidden;

    // 会话操作栏
    .session-action {
        padding: 12px 16px;
        border-bottom: 1px solid $border-color;
        display: flex;
        justify-content: space-between;
        align-items: center;

        &__create {
            width: calc(100% - 40px);
        }

        &__delete {
            color: #F56C6C;
            transition: color 0.2s;
            &:hover {
                color: #E53E3E;
            }
        }
    }

    // 会话列表容器
    .session-list-container {
        flex: 1;
        padding: 8px 0;
        overflow-y: auto;

        // 会话项
        .session-item {
            padding: 12px 16px;
            cursor: pointer;
            transition: all 0.2s;
            border-left: 3px solid transparent;
            position: relative;

            &:hover {
                background-color: $hover-color;
            }

            &--active {
                background-color: $light-primary;
                border-left-color: $primary-color;
            }

            &__header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 4px;
            }

            &__title {
                font-size: 14px;
                color: $text-primary;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                flex: 1;
                margin-right: 8px;
            }

            &__edit {
                opacity: 0;
                transition: opacity 0.2s;
                &:hover {
                    color: $primary-color;
                }
            }

            &:hover .session-item__edit {
                opacity: 1;
            }

            &__time {
                font-size: 12px;
                color: $text-tertiary;
            }
        }
    }

    // 配置面板
    .chat-config {
        border-top: 1px solid $border-color;
        padding: 8px;

        &__item {
            border-bottom: none !important;
        }

        &__form {
            padding: 8px 0;
        }

        &__form-item {
            margin-bottom: 12px;
        }

        &__slider {
            width: 100%;
        }
    }
}

// 右侧聊天主区域
.chat-main {
    flex: 1;
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: white;
    border-radius: $radius;
    box-shadow: $shadow;
    overflow: hidden;

    &__header {
        padding: 12px 16px;
        border-bottom: 1px solid $border-color;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #FCFCFC;
    }

    &__title {
        font-size: 15px;
        font-weight: 500;
        color: $text-primary;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    &__clear-btn {
        color: $text-tertiary;
        transition: color 0.2s;
        &:hover {
            color: #F56C6C;
        }
    }

    // 聊天历史容器
    .chat-history-container {
        flex: 1;
        padding: 24px;
        overflow-y: auto;
        background-color: #FAFAFA;

        .chat-history {
            max-width: 800px;
            margin: 0 auto;
            width: 100%;
        }

        // 空状态提示
        .empty-hint {
            padding: 40px 0;
            text-align: center;

            &__inner {
                max-width: 400px;
                margin: 0 auto;
            }

            &__tips {
                margin-top: 16px;
                color: $text-tertiary;
                font-size: 14px;
            }
        }

        // 无选中会话提示
        .no-session-hint {
            padding: 60px 0;
            text-align: center;

            &__inner {
                max-width: 300px;
                margin: 0 auto;
            }
        }

        // 消息列表
        .message-list {
            display: flex;
            flex-direction: column;
            gap: 20px;
            padding: 10px 0;
        }

        // 消息项
        .message-item {
            display: flex;
            gap: 12px;
            max-width: 100%;
            animation: fadeIn 0.3s ease-in-out;

            &--user {
                flex-direction: row-reverse;
            }

            &__avatar {
                flex-shrink: 0;
                width: 42px;
                height: 42px;
                box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);

                &--user {
                    background-color: $primary-color;
                    color: white;
                }

                &--assistant {
                    background-color: white;
                    color: $primary-color;
                    border: 1px solid $border-color;
                }
            }

            &__content {
                flex: 1;
                max-width: calc(100% - 54px);

                &:hover .message-item__time {
                    opacity: 1;
                }
            }

            &__nickname {
                font-size: 13px;
                color: $text-tertiary;
                margin-bottom: 4px;
                display: inline-block;
            }

            &__text {
                padding: 10px 14px;
                border-radius: $radius;
                line-height: 1.6;
                word-break: break-word;
                font-size: 14px;
                position: relative;
            }

            &__time {
                font-size: 12px;
                color: $text-tertiary;
                margin-top: 4px;
                opacity: 0.7;
                transition: opacity 0.2s;
                display: inline-block;
            }

            // 用户消息样式
            &--user {
                .message-item__text {
                    background-color: $user-color;
                    color: $text-primary;
                    border: 1px solid #D1E7FF;
                }
            }

            // AI消息样式
            &--assistant {
                .message-item__text {
                    background-color: white;
                    color: $text-primary;
                    border: 1px solid $border-color;
                }
            }
        }

        // 加载提示
        .loading-hint {
            padding: 16px;
            animation: fadeIn 0.3s ease-in-out;

            &__inner {
                max-width: 600px;
            }

            &__text {
                margin-top: 12px;
                font-size: 13px;
                color: $text-tertiary;
                text-align: center;
            }
        }
    }

    // 输入区域
    .chat-input-container {
        padding: 16px;
        border-top: 1px solid $border-color;
        background-color: white;

        &--disabled {
            background-color: #F9F9F9;
            .input-form__textarea {
                background-color: #F5F5F5;
                cursor: not-allowed;
            }
        }

        .input-form {
            &__item {
                margin-bottom: 12px;
            }

            &__textarea {
                border-radius: $radius;
                transition: border-color 0.2s;
                &:focus {
                    border-color: $primary-color;
                    box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.1);
                }
            }

            &__action {
                display: flex;
                justify-content: space-between;
                align-items: center;
            }

            &__tips {
                font-size: 12px;
                color: $text-tertiary;

                &__sending {
                    color: $primary-color;
                }
            }

            &__send-btn {
                min-width: 100px;
                padding: 8px 20px;
                border-radius: $radius;
            }
        }
    }
}

// 编辑标题表单
.edit-title-form {
    &__input {
        width: 100%;
    }
}

// 动画效果
@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

// 响应式调整
@media (max-width: 992px) {
    .chat-container {
        flex-direction: column;
    }

    .session-sidebar {
        width: 100%;
        height: 300px;
    }

    .chat-main {
        height: calc(100% - 300px);
    }
}

.input-form__textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s;
}

.input-form__textarea:focus {
  outline: none;
  border-color: #409eff; /* 聚焦时显示蓝色边框 */
}

.input-form__textarea:disabled {
  background-color: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}
</style>
